package com.eastfair.common.controller.micetother;

import com.eastfair.common.consts.CrmConstants;
import com.eastfair.common.dto.GmApiHostInfDto;
import com.eastfair.common.dto.GmApiHostInfDtos;
import com.eastfair.common.service.CrmHostSyncService;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.venuebooking.api.CustomerMainFeign;
import com.eastfair.venuebooking.vo.CustomerMainVO;
import core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 主办同步任务.
 *
 * @author dqq
 * @date 2023 /2/13
 */
@Component
@Slf4j
public class CrmHostSyncTask {

    @Value("${com.eastfair.projectId}")
    private Long projectId;

    @Resource
    private CustomerMainFeign customerMainFeign;

    @Resource
    private CrmHostSyncService crmHostSyncService;

    /**
     * Crm同步主办.
     */
    // @Scheduled(cron = "0/10 * * * * *")
    @XxlJob("syncHostInfo")
    public void syncHostInfo() {
        log.info("syncHostInfo - Crm同步主办任务启动");
        ContextUtil.setProjectId(projectId);
        GmApiHostInfDtos gmApiHostInfDtos =new GmApiHostInfDtos();
        R<List<CustomerMainVO>> r = customerMainFeign.queryForSyncCms();
        if(!r.getIsSuccess()){
            throw BizException.wrap(r.getCode(),r.getMsg());
        }
        List<CustomerMainVO> customerMainVOList = r.getData();
        if (customerMainVOList == null || customerMainVOList.isEmpty()) {
            log.info("syncHostInfo - 没有待同步的主办");
            return;
        }
        List<GmApiHostInfDto> gmApiHostInfDtoList = Lists.newArrayList();
        for(CustomerMainVO customerMainVO:customerMainVOList){
            GmApiHostInfDto gmApiHostInfDto =new GmApiHostInfDto();
            // 主办统一社会信用代码
            gmApiHostInfDto.setCrdtNo(customerMainVO.getUscc());
            gmApiHostInfDto.setCrdtTpcd(CrmConstants.CRDT_TPCD);
            gmApiHostInfDto.setCstId(customerMainVO.getId() + "");
            gmApiHostInfDto.setDelInd(customerMainVO.getIsDeleted().toString());
            gmApiHostInfDto.setDtSrc(CrmConstants.DT_SRC);
            // 主办资质等级 1 (一级),2 (二级),3 (三级)必传
            gmApiHostInfDto.setHostQfGrd("1");
            // 主办方类型 01 (组织7),02 (个人32)
            gmApiHostInfDto.setHostTp("01");
            gmApiHostInfDtoList.add(gmApiHostInfDto);
        }
        gmApiHostInfDtos.setDtos(gmApiHostInfDtoList);
        // 主办同步到CRM
        crmHostSyncService.syncHostInfo(gmApiHostInfDtos);
        // 更新主办状态为已同步
        List<Long> ids = customerMainVOList
                .stream()
                .map(CustomerMainVO::getId)
                .collect(Collectors.toList());
        customerMainFeign.updateCrmHasSync(ids);
    }
}